package com.mc.main;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

import android.graphics.Point;
import android.util.Log;


/**
 * @author Sajox
 * 
 * 		
 * Example Usage:
 * 
 * GraphHelper gh = new GraphHelper();
 * gh.addPoint(1, 1);
 * gh.addPoint(2, 2);
 * gh.addPoint(2, 3);
 * gh.addPoint(2, 4);
 * gh.addPoint(2, 5);
 * 		
 * for(Point p : gh.getAllPoints()){
 *   System.out.println("X: " + p.x + " Y: " + p.y);
 * }
 * 		
 * for(Point p : gh.getLastPoints(2)){
 *   System.out.println("X: " + p.x + " Y: " + p.y);
 * }
 *
 */

public class GraphHelper{
	private List<Point> graph = new ArrayList<Point>();
	
	/**
	 * @param x  x coordinate
	 * @param y  y coordinate
	 */
	public synchronized void addPoint(int x, int y){
		graph.add(new Point(x, y));
	}
	
	/**
	 * @param p Point to add to graph
	 */
	public synchronized void addPoint(Point p){
		graph.add(p);
	}
	
	/**
	 * @param p First occurrence of Point to remove from graph
	 * @return true if Point was removed from graph
	 */
	public synchronized boolean removePoint(Point p){
		return graph.remove(p);
	}
	
	/**
	 * @return Point array with all Points in graph
	 */
	public synchronized Point[] getAllPoints(){
		Point[] p;

		if(!graph.isEmpty()){
			 p = new Point[graph.size()];
			return graph.toArray(p);
		}else{
			p = new Point[0];
		}
		
		return p;
	}
	
	/**
	 * @param x, The last x points to be returned.  
	 * @return The array of Points
	 */
	public synchronized Point[] getLastPoints(int x){
		int size = graph.size();
		int startAt = (size > x) ? (size - x) : 0;
		Point[] p = (size > x) ? (new Point[x]) : new Point[size];
		try {
		if(!graph.isEmpty()){
			ListIterator<Point> li = graph.listIterator(startAt);
			
			for(int i=0;i < p.length; i++){
				if(li.hasNext()){
					p[i] = (Point)li.next();
				}
			}
					
			return p;
		}else{
			p = new Point[0];
		}
		} catch (Exception e) {
			Log.v("TAG", e.toString());
			
		
		}
		
		return p;
	}
	
	/**
	 * @return Returns last Point in graph or null
	 */
	public synchronized Point getLastPoint(){
		if(!graph.isEmpty()){
			return graph.get(graph.size());
		}
		
		return null;
	}
	
	/**
	 * 
	 * @return Returns true if empty else false
	 */
	public synchronized boolean isEmpty(){
		if(graph.isEmpty())
			return true;
		return false;
	}
}